const Controller = require('../core/base_controller');

const assert = require('assert');

class AppController extends Controller {

  //钉钉登录
  async login() {
    const { app, app: { dd }, ctx, ctx: { session } } = this;

    let { code, userid } = this.param

    ctx.logger.debug(`登录参数:code: ${code}, userid: ${userid}`);


    if (!userid) {
      let userinfo = await dd.user.getuserinfo({ code })
      ctx.logger.debug(`交换code得到用户信息 ${userinfo}`);

      userid = userinfo.userid
    }

    // 通过参数查询出具体的user对象，大致如下
    const user = await app.table('user').findOne({
      where: {
        userid
      }
    })

    ctx.logger.debug(`通过userid查询用户 ${user}`);

    //this.assert(user, '不存在该用户，请先通知管理员同步用户数据！' + userid)
    this.assert(user, `登录参数:code: ${code}, userid: ${userid}`)

    session.user = {
      userid: user.userid,
      username: user.name,
      role: user.role,
    };

    // 模拟登陆
    const token = app.jwt.sign(user, app.config.jwt.secret);
    ctx.cookies.set('Authorization', token);
    // 查询用户权限
    const power = await app.table('role_power').findAll(
      {
        where: {
          role_id: user.role,
        }
      }
    );
    //查询字典数据
    const dic = await app.table('dictionary').findAll()
    ctx.success({
      power, dic, userid
    });
  }

  async detail() {
    const { ctx, app } = this;

    let { user: { userid } } = ctx.state

    const user = await app.table('user').findOne({
      where: {
        userid
      }
    });
    ctx.success(user);
  }

  //获取用户信息，包含权限
  async getUserInfo() {
    const { app, ctx } = this

    let { user } = ctx.state
    let power = await this.service.user.getUserPower({ userid: user.userid })

    this.success(power)
  }

  //获取用户列表
  async index() {
    const { app, ctx } = this
    const { name } = this.param
    const where = name ? { name } : null;
    let users = await this.service.user.index(where)
    this.success(users)
  }

  //修改用户角色
  async setRole() {
    const { app, ctx } = this
    const { userid, department } = this.param
    let users = await this.service.user.setRole({
      userid, department
    })
    this.success()
  }

}
module.exports = AppController;
